<template>
  <div class="box">
    <div class="searcharea">
      <!-- 搜索 -->
      <el-row>
        <el-col :span="24">
          <div class="query">
            <el-form :inline="true" :model="queryRoleinfoParam" class="demo-form-inline">
              <el-form-item label="编号">
                <el-input v-model="queryRoleinfoParam.RoleNo" placeholder="请输入" clearable style="width: 200px" />
              </el-form-item>

              <el-form-item label="角色名称">
                <el-input v-model="queryRoleinfoParam.RoleName" placeholder="请输入" clearable style="width: 200px" />
              </el-form-item>

              <el-form-item>
                <el-button type="primary" :icon="Search" @click="SearchRoleinfo()">搜索</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="contentarea">
      <!-- 功能按钮 -->
      <el-row>
        <el-col :span="24">
          <div class="functionbutton">
            <el-button type="primary" plain @click="addRoleinfo()">添加</el-button>
            <el-button type="danger" plain @click="batchDeletionRoleinfo()">批量删除</el-button>
          </div>
        </el-col>
        <el-dialog v-model="centerDialogVisible" title="添加角色" width="30%" align-center>
          <el-form
            ref="CreateRoleinfoForm"
            :model="CreateRoleinfoForm"
            :rules="CreateRoleinfoRules"
            label-width="auto"
            style="padding: 20px"
          >
            <el-form-item label="编号">
              <el-input v-model="CreateRoleinfoForm.RoleNo" placeholder="不输入则自动生成"> </el-input>
            </el-form-item>
            <el-form-item prop="RoleName" label="角色名称">
              <el-input v-model="CreateRoleinfoForm.RoleName" placeholder="请输入"> </el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="CreateRoleinfoForm.Remark" type="textarea" />
            </el-form-item>
          </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button @click="centerDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="CreateRoleinfoDialog()">确认</el-button>
            </div>
          </template>
        </el-dialog>
      </el-row>

      <!-- 数据表格 -->
      <el-row>
        <el-col :span="24">
          <div>
            <el-table
              :data="tableData"
              v-loading="tableloading"
              border
              style="width: 100%"
              max-height="400px"
              :selection="selectedRows"
              @selection-change="handleSelectionChange"
              @row-click="getRowkey"
              show-overflow-tooltip
              empty-text="暂无数据"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="序号" />
              <el-table-column prop="roleNo" label="编号" width="180" />
              <el-table-column prop="roleName" label="名称" />
              <el-table-column prop="remark" label="备注" />
              <el-table-column prop="creator" label="创建人" />
              <el-table-column prop="updator" label="修改人" />
              <el-table-column prop="createtime" label="创建时间" width="180" :formatter="formatColumnTime" />
              <el-table-column prop="updateDate" label="更新时间" width="180" :formatter="formatColumnTime" />
              <el-table-column fixed="right" label="操作" width="230">
                <template #default="scope">
                  <el-button type="success" plain size="small" @click="RoleinfoAuthoritySingle(scope.row.id)">
                    权限配置
                  </el-button>
                  <el-button type="danger" plain size="small" @click="DeleteRoleinfoSingle(scope.row.id)">
                    删除
                  </el-button>
                  <el-button type="primary" plain size="small" @click="UpdateRoleinfo(scope.row)">更新</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
        <!-- 权限配置 -->
        <el-dialog v-model="AuthorityDialogVisible" title="权限配置" width="30%" align-center>
          <el-tree
            :data="AuthorityRoleinfodata"
            show-checkbox
            :default-expand-all="false"
            node-key="id"
            ref="tree"
            highlight-current
            :default-checked-keys="AuthorityRoleinfoAcquiesceData"
            :props="defaultProps"
          >
          </el-tree>

          <template #footer>
            <div class="dialog-footer">
              <el-button @click="AuthorityDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="RoleinfoAuthorityDialog()">确认</el-button>
            </div>
          </template>
        </el-dialog>
        <!-- 修改角色 -->
        <el-dialog v-model="UpdateDialogVisible" title="修改角色" width="30%" align-center>
          <el-form
            ref="UpdateRoleinfoForm"
            :model="UpdateRoleinfoForm"
            :rules="CreateRoleinfoRules"
            label-width="auto"
            style="padding: 20px"
          >
            <el-form-item label="编号">
              <el-input v-model="UpdateRoleinfoForm.RoleNo" disabled placeholder="不输入则自动生成"> </el-input>
            </el-form-item>
            <el-form-item prop="RoleName" label="角色名称">
              <el-input v-model="UpdateRoleinfoForm.RoleName" placeholder="请输入"> </el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="UpdateRoleinfoForm.Remark" type="textarea" />
            </el-form-item>
          </el-form>

          <template #footer>
            <div class="dialog-footer">
              <el-button @click="UpdateDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="UpdateRoleinfoDialog()">确认</el-button>
            </div>
          </template>
        </el-dialog>
      </el-row>

      <!-- 分页 -->
      <el-row>
        <el-col :span="24">
          <div class="demo-pagination-block" style="display: flex; justify-content: flex-end">
            <el-config-provider :locale="zhCn">
              <el-pagination
                v-model:current-page="queryRoleinfoParam.PageIndex"
                v-model:page-size="queryRoleinfoParam.PageSize"
                :page-sizes="[100, 200, 300, 400]"
                :small="false"
                :disabled="false"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="queryRoleinfoParam.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              >
              </el-pagination>
            </el-config-provider>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script >
import { Search } from '@element-plus/icons-vue'
import {
  ApiGetBasicData_RoleinfoPageListAsync,
  GetBasicData_Roleinfo_MenuInfoByIdTreeListAsync,
  ApiBatchDeletionBasicData_RoleinfoAsync,
  ApiUpdateBasicData_RoleinfoAsync,
  ApiCreateBasicData_Roleinfo_MenuInfoAsync,
  ApiCreateBasicData_RoleinfoAsync
} from '@/api/basic/basicDataRoleinfoApi'

import { formatTime, capitalizeFirstLetter } from '../../utils/index'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessageBox, ElNotification } from 'element-plus'

export default {
  name: 'RoleinfoView',
  data() {
    return {
      selectedRoleMenuInfodata: {}, // 用于存储选中的角色id
      AuthorityDialogVisible: false,
      AuthorityRoleinfodata: [],
      AuthorityRoleinfoAcquiesceData: [],
      tableloading: false,
      UpdateDialogVisible: false,
      UpdateRoleinfoForm: {},
      RoleinfotOptions: null,
      CreateRoleinfoForm: {},
      CreateRoleinfoRules: {
        RoleName: [{ required: true, trigger: 'blur', message: '角色名称不能为空' }]
      },
      centerDialogVisible: false,
      selectedRows: [], // 存储选中的行数据
      queryRoleinfoParam: {
        PageIndex: 1,
        PageSize: 100
      },
      tableData: [] // 表格数据
    }
  },
  setup() {
    return {
      Search,
      zhCn
    }
  },
  created() {
    this.SearchRoleinfo()
  },
  methods: {
    //配置权限
    RoleinfoAuthoritySingle(res) {
      this.AuthorityDialogVisible = true
      this.selectedRoleMenuInfodata.RoleinfoId = res
      GetBasicData_Roleinfo_MenuInfoByIdTreeListAsync(this.selectedRoleMenuInfodata)
        .then((res) => {
          const datas = res.data.data
          // 获取所有节点的 id 和 label，
          const getAllIdsAndLabels = (nodes) => {
            const result = []
            // 遍历传入的节点数组
            nodes.forEach((node) => {
              // 创建一个新的节点对象 newNode
              const newNode = {
                id: node.id,
                label: node.menuInfoName,
                children: []
              }
              // 如果原始节点有 children 属性（即它是父节点）
              if (node.children) {
                // 递归调用 getAllIdsAndLabels 函数，处理子节点，并将结果赋值给 newNode 的 children 属性
                newNode.children = getAllIdsAndLabels(node.children)
              }
              result.push(newNode)
            })
            return result
          }
          //获取菜单集合
          this.AuthorityRoleinfodata = getAllIdsAndLabels(datas.menuInfos)
          // //获取已经绑定的菜单id
          this.AuthorityRoleinfoAcquiesceData = datas.roleinfoMenuInfoIds
        })
        .catch()
    },
    // 配置权限确认
    RoleinfoAuthorityDialog() {
      // 获取子级的key
      const childMenu = this.$refs.tree.getCheckedKeys()
      // 获取父级的key
      const partMenu = this.$refs.tree.getHalfCheckedKeys()
      // 合并数据
      this.selectedRoleMenuInfodata.MenuInfoIds = partMenu.concat(childMenu)

      ApiCreateBasicData_Roleinfo_MenuInfoAsync(this.selectedRoleMenuInfodata)
        .then((res) => {
          if (res.data.data) {
            ElNotification({
              message: '更新成功',
              offset: 100,
              type: 'success',
              duration: 2000
            })
            // this.centerDialogVisible = false
          }
        })
        .catch()
    },
    //确认更新
    UpdateRoleinfoDialog() {
      this.$refs.UpdateRoleinfoForm.validate((valid) => {
        if (valid) {
          ApiUpdateBasicData_RoleinfoAsync(this.UpdateRoleinfoForm)
            .then((res) => {
              if (res.data.data) {
                ElNotification({
                  message: '更新成功',
                  offset: 100,
                  type: 'success',
                  duration: 2000
                })
                this.UpdateDialogVisible = false
                this.SearchRoleinfo()
              }
            })
            .catch()
        }
      })
    },
    //更新角色
    UpdateRoleinfo(res) {
      this.UpdateDialogVisible = true
      this.UpdateRoleinfoForm = capitalizeFirstLetter(res)
    },
    //删除角色
    DeleteRoleinfoSingle(res) {
      this.selectedRows = []
      this.selectedRows.push(res)
      this.batchDeletionRoleinfo()
    },
    //添加角色
    CreateRoleinfoDialog() {
      this.$refs.CreateRoleinfoForm.validate((valid) => {
        if (valid) {
          ApiCreateBasicData_RoleinfoAsync(this.CreateRoleinfoForm)
            .then((res) => {
              if (res.data.data) {
                ElNotification({
                  message: '添加角色成功',
                  offset: 100,
                  type: 'success',
                  duration: 2000
                })
                this.centerDialogVisible = false
                this.SearchRoleinfo()
              }
            })
            .catch()
        }
      })
    },

    //获取角色选择项
    handleSelectionChange(select) {
      // 提取传递过来的对象中的"id"字段，并存储到this.selectedRows中
      this.selectedRows = select.map((item) => item.id)
    },
    //添加角色
    addRoleinfo() {
      this.centerDialogVisible = true
    },
    //指删除角色
    batchDeletionRoleinfo() {
      if (this.selectedRows.length < 1) {
        ElNotification({
          message: '请先选择一条或更多信息',
          type: 'warning',
          offset: 100,
          duration: 2000
        })
        return
      }
      ElMessageBox.confirm('确实要删除这些信息吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          ApiBatchDeletionBasicData_RoleinfoAsync(this.selectedRows)
            .then((res) => {
              if (res.data.data) {
                ElNotification({
                  message: '删除成功',
                  offset: 100,
                  type: 'success',
                  duration: 2000
                })
                this.selectedRows = []
                this.SearchRoleinfo()
              }
            })
            .catch(() => {
              this.selectedRows = []
            })
        })
        .catch(() => {
          this.selectedRows = []
        })
    },
    //时间转换
    formatColumnTime(row, column, time) {
      return formatTime(time)
    },

    //每页条数
    handleSizeChange(e) {
      this.queryRoleinfoParam.PageSize = e
      this.SearchRoleinfo()
    },

    // 搜索
    SearchRoleinfo() {
      this.tableloading = true
      ApiGetBasicData_RoleinfoPageListAsync(this.queryRoleinfoParam)
        .then((res) => {
          this.tableData = res.data.data
          this.queryRoleinfoParam.PageIndex = res.data.pageIndex
          this.queryRoleinfoParam.PageSize = res.data.pageSize
          this.queryRoleinfoParam.totalCount = res.data.totalCount
        })
        .finally(() => {
          this.tableloading = false
        })
    }
  }
}
</script>

<style lang="less"  scoped>
@import '../../assets/globle/index.css';
</style>